#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <mqueue.h>

#include "config.h"
#include "bal_posting.h"

#define _SEUIL 900

void* BalPosting()
{
	// Initialisation ------------------------------------

	srand(time(0));
	unsigned int nb_alea;
	unsigned int time_sleep;
	unsigned int msgPrio = 0;
	mqd_t queue_versEcriture;
	MSG_versEcriture msg_versEcriture;

	// opening BAL_versEcriture, WRITE only
	queue_versEcriture =  mq_open(BAL_versEcriture, O_WRONLY);



	// Running loop -------------------------------------

	while(1)
	{
		
		nb_alea = rand()%1000;
		if(nb_alea <= _SEUIL)
		{ // send log msg
			msg_versEcriture.typeMessage = ARCHIVAGE;
			msg_versEcriture.message = PAL_OK;
			msg_versEcriture.cartonEnCours = 0;
		} 
		else
		{ // send an error msg
			msg_versEcriture.typeMessage = ERREUR;
			msg_versEcriture.message = ERR_IMP;
			msg_versEcriture.cartonEnCours = 42;
		}
		msg_versEcriture.heure = time(NULL);
		msg_versEcriture.numLot = 1768;

		if (0 != mq_send(queue_versEcriture, (const char *)&msg_versEcriture, sizeof(MSG_versEcriture), msgPrio))
		{
			perror ("[BALPosting] Failed to Send BAL_versEcriture:");
		}

		time_sleep = ( rand()%1000 ) / 200; // sleep until 5 sec
		sleep(time_sleep);
	}
}
